﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using System.Collections.Concurrent;
using System.Net.Http.Headers;
using SSharing.Frameworks.Common.Extends;
using System.Net;

namespace ConcurrentTools
{
    public partial class Form1 : Form
    {
        private string Path = System.AppDomain.CurrentDomain.BaseDirectory + "/config.txt";

        protected Config mConfig = null;

        protected Config Config
        {
            get
            {
                mConfig = new Config()
                {
                    Url = this.txtUrl.Text.Trim(),
                    Body = this.txtBody.Text.Trim(),
                    Head = this.txtHeader.Text.Trim()
                };
                return mConfig;
            }
            set
            {
                mConfig = value;
                if (mConfig == null)
                {
                    return;
                }
                this.txtBody.Text = mConfig.Body;
                this.txtHeader.Text = mConfig.Head;
                this.txtUrl.Text = mConfig.Url;
            }
        }

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;//fix从不是创建控件的线程访问它
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var url = GetUrl();
            var headers = GetHeader();
            var body = GetBody();
            var comparssMethod = GetDecomparessMethod();

            var taskArr = GetTaskArr();
            for (int i = 0; i < taskArr.Length; i++)
            {
                taskArr[i] = HttpHelper.Post(url, headers, body, comparssMethod, AppendMsg, i);
            }
            Task.WhenAll(taskArr);
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            var url = GetUrl();
            var headers = GetHeader();
            var body = GetBody();
            var comparssMethod = GetDecomparessMethod();

            var taskArr = GetTaskArr();
            for (int i = 0; i < taskArr.Length; i++)
            {
                taskArr[i] = HttpHelper.Get(url, headers, comparssMethod, AppendMsg, i);
            }
            Task.WhenAll(taskArr);
        }

        private int GetQty()
        {
            return txtQty.Text.Trim().ToInt(500);
        }

        private Task[] GetTaskArr()
        {
            Task[] taskArr = new Task[GetQty()];
            return taskArr;
        }

        private string GetUrl()
        {
            return this.txtUrl.Text.Trim();
        }
        private Dictionary<string, string> GetHeader()
        {
            var dics = new Dictionary<string, string>();

            var headerStr = this.txtHeader.Text.Trim();
            var lines = headerStr.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                if (string.IsNullOrWhiteSpace(line)) continue;

                var index = line.IndexOf(":");
                if (index < 0) continue;

                var key = line.Substring(0, index);

                var val = line.Substring(index + 1, line.Length - index - 1);
                dics[key] = val.Trim().TrimEnd(';');
            }
            return dics;
        }
        private string GetBody()
        {
            return this.txtBody.Text.Trim();
        }
        private DecompressionMethods GetDecomparessMethod()
        {
            return (DecompressionMethods)this.cmbCompress.SelectedIndex;
        }

        private void AppendMsg(string msg, int index)
        {
            richTextBox1.AppendText(string.Format("{0}=>{1}-{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), index.ToString().PadLeft(3, '0'), msg.ToString()));
            richTextBox1.AppendText(Environment.NewLine);
        }

        private void 加载配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var filePath = Path;
            using (var dialog = new OpenFileDialog())
            {
                dialog.Multiselect = false;
                dialog.Title = "请选择文件";
                dialog.Filter = "所有文件(*.*)|*.*";
                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    filePath = dialog.FileName;
                }
            }

            var rst = Config.Load(filePath);
            if (!rst.IsSuccess)
            {
                MessageBox.Show(rst.Message);
                return;
            }
            Config = rst.Data;
        }

        private void 保存配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config.Save(Config, Path);
            MessageBox.Show("保存成功");
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var msg = string.Format("此工具仅适用于程序的压力测试，切勿用于非法用途！{0}{0}有疑问请联系作者哒哒，QQ：80789967", Environment.NewLine);
            MessageBox.Show(msg);
        }
    }
}
